package com.chinawlx.wlxteacher.ui.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chinawlx.wlxteacher.R;
import com.chinawlx.wlxteacher.network.WLXHttpRxHelper;
import com.chinawlx.wlxteacher.network.bean.WLXRollCallBean;
import com.chinawlx.wlxteacher.ui.activity.WLXCourseRollCallActivity;
import com.chinawlx.wlxteacher.utils.ToPinyinUtils;
import com.chinawlx.wlxteacher.utils.WLXDateUtil;
import com.chinawlx.wlxteacher.utils.WLXGreenDaoUtil;
import com.chinawlx.wlxteacher.utils.WLXLogUtil;
import com.chinawlx.wlxteacher.widget.WLXCustomToast;
import com.chinawlx.wlxteacher.wlx_student;
import com.chinawlx.wlxteacher.wlx_studentDao;
import com.chinawlx.wlxteacher.wlx_student_order_detail;
import com.chinawlx.wlxteacher.wlx_student_order_detailDao;
import com.chinawlx.wlxteacher.wlx_student_study;
import com.chinawlx.wlxteacher.wlx_student_studyDao;

import java.util.HashMap;
import java.util.List;

import rx.Subscriber;

import static com.chinawlx.wlxteacher.utils.WLXConstant.student_id;

/**
 * Created by wlx on 16/10/11.
 */

public class WLXStudentRollCallAdapter extends RecyclerView.Adapter<WLXStudentRollCallAdapter
        .StudentViewHolder> {
    private Context mContext;
    private PopupWindow mPopupWindow;       //长按学生弹出
    private int rollCallNum = 0;          //记录点名人数
    private int leaveNum=0;               //记录请假人数
    private int truantNum=0;
    private List<WLXCourseRollCallActivity.StudentInfoBean> wlxStudents;
    private TextView attendance;
    private TextView leave;
    private TextView truant;
    private TextView confirm;
    HashMap<Integer,String> map =new HashMap<>();
    HashMap<Integer,String> tempMap =new HashMap<>();
    private String studentIds="";
    private String gradeId;
    private String scheduleId;
    private int sendRequestCount=0;     //记录用户发送请求次数

    /**
     * @param mContext    上下文
     * @param wlxStudents 学生集合
     * @param attendance  出勤的人数
     * @param confirm     确认
     */
    public WLXStudentRollCallAdapter(Context mContext, List<WLXCourseRollCallActivity
            .StudentInfoBean> wlxStudents, TextView attendance, TextView confirm,TextView leave,TextView truant,String gradeId,String scheduleId) {
        this.mContext = mContext;
        this.wlxStudents = wlxStudents;
        this.attendance = attendance;
        this.leave = leave;
        this.truant = truant;
        this.confirm = confirm;
        this.gradeId = gradeId;
        this.scheduleId = scheduleId;
//        for (int i = 0; i < wlxStudents.size(); i++) {
//            map.put(wlxStudents.get(i).getStudent_id(),wlxStudents.get(i))
//        }
    }

    @Override
    public WLXStudentRollCallAdapter.StudentViewHolder onCreateViewHolder(ViewGroup parent, int
            viewType) {
        WLXStudentRollCallAdapter.StudentViewHolder holder = new WLXStudentRollCallAdapter
                .StudentViewHolder(View.inflate
                (mContext, R.layout.item_call_roll, null));
        return holder;
    }

    @Override
    public void onBindViewHolder(final WLXStudentRollCallAdapter.StudentViewHolder holder, final int
            position) {
        holder.name.setText(wlxStudents.get(position).getName());
        String url = wlxStudents.get(position).getIcon();
        Glide.with(mContext).load(url).into(holder.icon);
        holder.icon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!holder.iconClick.isShown()) {
                    holder.iconClick.setVisibility(View.VISIBLE);
                    rollCallNum++;
                    // TODO: 16/10/21 添加学习id和study
                    // id-study
                    int student_id = wlxStudents.get(position).getStudent_id();

                    WLXLogUtil.printE(student_id+" : "+wlxStudents.get(position).getName());
                    map.put(student_id,"-study");
                    if (holder.status.isShown()) {
                        String status = holder.status.getText().toString().trim();
                        if (status.equals("请")) {
                            leaveNum--;
                            map.put(student_id,"-study");
                        }else {
                            truantNum--;
                            map.put(student_id,"-study");

                        }
                        holder.status.setVisibility(View.GONE);

                    }
                } else {
                    // TODO: 16/10/21 删除学习id和study
                    map.remove(student_id);
                    holder.iconClick.setVisibility(View.GONE);
                    rollCallNum--;
                }

                if (rollCallNum != 0||leaveNum!=0||truantNum!=0) {
                    confirm.setVisibility(View.VISIBLE);
                } else {
                    confirm.setVisibility(View.GONE);
                }
                attendance.setText(rollCallNum + "人");
                leave.setText(leaveNum + "人");
                truant.setText(truantNum + "人");
            }
        });
        holder.icon.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (!holder.iconClick.isShown()) {
//                    showPopupwindow(holder.icon,holder.status);
                    showPopupwindow(holder,position);
                }
                return true;
            }
        });
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        //发送点名请求
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //将第一次发送的请求map记录下来,当用户再次发送请求时去判断用户两次发送的请求是否一致

//                tempMap=map;
                for (Integer key : map.keySet()) {
//                    tempMap.clear();
                    tempMap.put(key,map.get(key));
                    WLXLogUtil.printE("key= "+key+"value= "+map.get(key));
                    studentIds+=key+map.get(key)+",";
                }
                String studentIdsNew = studentIds.substring(0,studentIds.length()-1);
                studentIds="";
                WLXLogUtil.printE(studentIdsNew);

                requestNet(studentIdsNew);
//
//                if (sendRequestCount>0) {
//                    if (map.equals(tempMap)) {
//                        WLXCustomToast.show("两次请求一致");
//                    }else{
//                        WLXCustomToast.show("不一致");
//                    }
//                }else {
//                    WLXCustomToast.show("第一次请求");
//                }
//                sendRequestCount++;
////                requestNet(studentIdsNew);
//                WLXLogUtil.printE("清空前 "+map+"tempMap: "+tempMap);
//                map.clear();
//                WLXLogUtil.printE("清空后 "+map+"tempMap: "+tempMap);

            }
        });
    }


    @Override
    public int getItemCount() {
        return wlxStudents == null ? 0 : wlxStudents.size();
    }

    class StudentViewHolder extends RecyclerView.ViewHolder {
        ImageView icon;
        ImageView iconClick;
        TextView name;
        TextView status;

        public StudentViewHolder(View itemView) {
            super(itemView);
            icon = (ImageView) itemView.findViewById(R.id.iv_test);
            iconClick = (ImageView) itemView.findViewById(R.id.iv_test_click);
            name = (TextView) itemView.findViewById(R.id.tv_test);
            status = (TextView) itemView.findViewById(R.id.tv_status);
        }
    }

//    private void showPopupwindow(View v, final TextView status) {
    private void showPopupwindow(final StudentViewHolder holder, final int position) {
        View popView = LayoutInflater.from(mContext).inflate(R.layout.popupwindow_select, null);
        mPopupWindow = new PopupWindow();
        mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setContentView(popView);
        // 允许点击外部消失,部分机型无效
        mPopupWindow.setOutsideTouchable(true);
        //新方法,点击外部消失.
        mPopupWindow.setFocusable(false);
        //计算popWindow的偏移量，首先测量popWindow的宽高
        mPopupWindow.getContentView().measure(0, 0);
        int height = mPopupWindow.getContentView().getMeasuredHeight();
        int width = mPopupWindow.getContentView().getMeasuredWidth();
//        int offsetX = v.getWidth() / 2 - width / 2;
//        int offsetY = v.getHeight() + height;
        int offsetX = holder.icon.getWidth() / 2 - width / 2;
        int offsetY = holder.icon.getHeight() + height;
        mPopupWindow.showAsDropDown(holder.icon, offsetX, -offsetY);
        mPopupWindow.update();
        popView.findViewById(R.id.tv_leave_pop).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopupWindow.dismiss();
                mPopupWindow = null;
                holder.status.setVisibility(View.VISIBLE);
                holder.status.setText("请");
                String status = holder.status.getText().toString().trim();
                if (holder.status.isShown()&&status.equals("请")) {
                    leaveNum++;
                    leave.setText(leaveNum+"人");
                    int student_id = wlxStudents.get(position).getStudent_id();
                    WLXLogUtil.printE(student_id+" : "+wlxStudents.get(position).getName());
                    map.put(student_id,"-leave");
                }
                if (leaveNum!=0) {
                    confirm.setVisibility(View.VISIBLE);
                }else {
                    confirm.setVisibility(View.GONE);

                }
            }
        });
        popView.findViewById(R.id.tv_truant_pop).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopupWindow.dismiss();
                mPopupWindow = null;
                holder.status.setVisibility(View.VISIBLE);
                holder.status.setText("旷");
                String status = holder.status.getText().toString().trim();
                if (holder.status.isShown()&&status.equals("旷")) {
                    truantNum++;
                    truant.setText(truantNum+"人");
                    int student_id = wlxStudents.get(position).getStudent_id();
                    WLXLogUtil.printE(student_id+" : "+wlxStudents.get(position).getName());
                    map.put(student_id,"-truant");
                }
                if (truantNum!=0) {
                    confirm.setVisibility(View.VISIBLE);
                }else {
                    confirm.setVisibility(View.GONE);

                }
            }
        });

    }
    private int isAddition;
    private void requestNet(String studentIds) {
        /*
         *   第一种情况如果课程的isAddition = 1 并且 addition_student_ids不等于空字符串，
         *   则表明此课程为多个学生加课的课程，需要对课程的addition_student_ids字段进行切割拿到学生id数组，
         *   根据学生id查询wlx_student表，同时根据学生id、课程id和班级id查询wlx_student_study表；
         *
         *   第二种情况则为正常上课或者全班加课，根据课程id和班级id请求数据拿到该班级的订单数据，
         *   根据订单的学生id查询wlx_student表，同时根据学生id、课程id和班级id查询wlx_student_study表；
         */
//        if (!TextUtils.isEmpty(studentIds) && isAddition == 1) {
//            WLXHttpRxHelper.getInstance().callRollIdsNotNull(gradeId, scheduleId, studentIds, new
//                    Subscriber<WLXRollCallBean>() {
//
//
//                        @Override
//                        public void onCompleted() {
//                        }
//
//
//                        @Override
//                        public void onError(Throwable e) {
//
//                        }
//
//                        @Override
//                        public void onNext(WLXRollCallBean wlxRollCallBean) {
//
//                        }
//                    });
//        } else {
//            WLXHttpRxHelper.getInstance().callRollIdsNull(gradeId, scheduleId, studentIds, new
//                    Subscriber<WLXRollCallBean>() {
//                        @Override
//                        public void onCompleted() {
//
//                        }
//
//                        @Override
//                        public void onError(Throwable e) {
//
//                        }
//
//                        @Override
//                        public void onNext(WLXRollCallBean wlxRollCallBean) {
//                            if (wlxRollCallBean.getCode() == 0) {
//                                savaStudentOrderDetailTable(wlxRollCallBean);
//                                saveStudentStudyTable(wlxRollCallBean);
//                                saveStudentTable(wlxRollCallBean);
//                            }
//                        }
//                    });
//        }
        if (!TextUtils.isEmpty(studentIds)){
            WLXHttpRxHelper.getInstance().callRollIdsNotNull(gradeId, scheduleId, studentIds, new
                    Subscriber<WLXRollCallBean>() {


                        @Override
                        public void onCompleted() {
                        }


                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onNext(WLXRollCallBean wlxRollCallBean) {
                            savaStudentOrderDetailTable(wlxRollCallBean);
                            saveStudentStudyTable(wlxRollCallBean);
                            saveStudentTable(wlxRollCallBean);
                        }
                    });
        }else {
            WLXCustomToast.show("请选择学生");
        }

    }

    /**
     * 存储 wlx_student 表
     *
     * @param wlxRollCallBean
     */
    private void saveStudentTable(WLXRollCallBean wlxRollCallBean) {
        List<WLXRollCallBean.DataBean.StudentListBean> studentList = wlxRollCallBean.getData()
                .getStudent_list();
        for (WLXRollCallBean.DataBean.StudentListBean studentListBean : studentList) {
            String student_id = Integer.toString(studentListBean.getId());
            int family_user_id = studentListBean.getFamily_user_id();
            String realname = studentListBean.getRealname();
            String realname_pinyin = ToPinyinUtils.getPinYin(realname);
            long birthday = WLXDateUtil.getStringToDate(studentListBean.getBirthday());
            String mobile = studentListBean.getMobile();
            String avatar_url = studentListBean.getAvatar().getUrl();
            String remark = studentListBean.getRemark();
            String sex_code = studentListBean.getSex().getKey();
            long last_modified_date = WLXDateUtil.getStringToDate(studentListBean
                    .getLast_modified_date());
            wlx_student wlx_student = new wlx_student(student_id, family_user_id,
                    realname, realname_pinyin, birthday, mobile, avatar_url, remark,
                    sex_code, last_modified_date);
            List<wlx_student> wlx_students = WLXGreenDaoUtil
                    .getStudentDao().queryBuilder().where(wlx_studentDao.Properties
                            .Student_id.eq(student_id)).list();
            if (wlx_students.size() > 0) {
                if (last_modified_date > wlx_students.get(0).getLast_modified_date()) {
                    WLXGreenDaoUtil.getStudentDao().update(wlx_student);
                }
            } else {
                WLXGreenDaoUtil.getStudentDao().insert(wlx_student);
            }
        }
    }

    /**
     * 存储 wlx_student_study 表
     *
     * @param wlxRollCallBean
     */
    private void saveStudentStudyTable(WLXRollCallBean wlxRollCallBean) {
        List<WLXRollCallBean.DataBean.StudyListBean> studyList =
                wlxRollCallBean.getData().getStudy_list();
        for (WLXRollCallBean.DataBean.StudyListBean studyListBean : studyList) {
            String student_study_id = Integer.toString(studyListBean.getId());
            int student_id = studyListBean.getStudent_id();
            int teacher_user_id = studyListBean.getTeacher_user_id();
            int grade_id = studyListBean.getGrade_id();
            int schedule_id = studyListBean.getSchedule_id();
            String student_remark = studyListBean.getStudent_remark();
            String teacher_remark = studyListBean.getTeacher_remark();
            String study_status_code = studyListBean.getStudy_status().getKey();
            String extend_info = (String) studyListBean.getExtend();
            long start_date = WLXDateUtil.getStringToDate(studyListBean.getStart_date());
            long end_date = WLXDateUtil.getStringToDate(studyListBean.getEnd_date());
            long last_modified_date = WLXDateUtil.getStringToDate(studyListBean
                    .getLast_modified_date());
            int version = studyListBean.getVersion();
            wlx_student_study wlxStudentStudy = new wlx_student_study(student_study_id,
                    student_id, teacher_user_id, grade_id, schedule_id,
                    student_remark, teacher_remark, study_status_code, extend_info, start_date,
                    end_date, last_modified_date, version);
            List<wlx_student_study> wlx_student_studies = WLXGreenDaoUtil.getStudentStudyDao()
                    .queryBuilder()
                    .where(wlx_student_studyDao.Properties.Student_study_id.eq(student_study_id))
                    .list();
            if (wlx_student_studies.size() > 0) {
                if (last_modified_date > wlx_student_studies.get(0).getLast_modified_date()) {
                    WLXGreenDaoUtil.getStudentStudyDao().update(wlxStudentStudy);
                } else {
                    WLXGreenDaoUtil.getStudentStudyDao().insert(wlxStudentStudy);
                }
            }
        }
    }

    /**
     * 存储 wlx_student_order_detail 表
     *
     * @param wlxRollCallBean
     */
    private void savaStudentOrderDetailTable(WLXRollCallBean wlxRollCallBean) {
        List<WLXRollCallBean.DataBean.OrderListBean> orderList =
                wlxRollCallBean.getData().getOrder_list();
        for (WLXRollCallBean.DataBean.OrderListBean orderListBean :
                orderList) {
            String student_order_detail_id = Integer.toString
                    (orderListBean.getOrder_id());
            int student_id = orderListBean.getStudent_id();
            int teacher_user_id = orderListBean.getTeacher_user_id();
            int family_user_id = orderListBean.getFamily_user_id();
            int org_user_id = orderListBean.getOrg_user_id();
            int space_id = orderListBean.getSpace_id();
            int classroom_id = orderListBean.getClassroom_id();
            int grade_id = orderListBean.getGrade_id();
            String grade_title = orderListBean.getGrade_title();
            int medal_count = orderListBean.getMedal_count();
            int homework_count = orderListBean.getHomework_count();
            String grade_type_code = orderListBean.getGrade_type().getKey();
            String grade_type_name = orderListBean.getGrade_type()
                    .getValue();
            String class_type_code = orderListBean.getClass_type()
                    .getCode();
            String class_type_name = orderListBean.getClass_type()
                    .getName();
            String class_child_type_code = orderListBean
                    .getClass_child_type().getCode();
            String class_child_type_name = orderListBean
                    .getClass_child_type().getName();
            int consume_number = orderListBean.getConsume_number();
            int balance_number = orderListBean.getBalance_number();
            int total_number = orderListBean.getTotal_number();
            long last_modified_date = WLXDateUtil.getStringToDate
                    (orderListBean.getLast_modified_date());

            wlx_student_order_detail wlxStudentOrderDetail = new
                    wlx_student_order_detail(student_order_detail_id,
                    student_id, teacher_user_id, family_user_id,
                    org_user_id, space_id, classroom_id, grade_id,
                    grade_title, medal_count, homework_count,
                    grade_type_code,
                    grade_type_name, class_type_code, class_type_name,
                    class_child_type_code, class_child_type_name,
                    consume_number, balance_number, total_number,
                    last_modified_date);
            List<wlx_student_order_detail> wlx_student_order_details =
                    WLXGreenDaoUtil
                            .getStudentOrderDetailDao().queryBuilder()
                            .where(wlx_student_order_detailDao.Properties
                                    .Student_order_detail_id.eq
                                            (student_order_detail_id))
                            .list();
            if (wlx_student_order_details.size() > 0) {
                if (last_modified_date > wlx_student_order_details.get(0)
                        .getLast_modified_date()) {
                    WLXGreenDaoUtil.getStudentOrderDetailDao().update
                            (wlxStudentOrderDetail);
                } else {
                    WLXGreenDaoUtil.getStudentOrderDetailDao().insert
                            (wlxStudentOrderDetail);
                }
            }
        }
    }
}
